<!--城乡房屋安全核查表-->
<template>
    <div id="houseSafetyChecklist">
        <div class="JBXX">
            <p class="title">城乡房屋安全核查表</p>
            <van-field v-model="fromData.inspectPerson" label="核查人" :readonly="disabled"/>
            <van-field v-model="fromData.inspectDate" label="核查时间" @click="disabled?'':showPickerq=true" :readonly="disabled"/>
            <van-popup v-model="showPickerq" position="bottom">
                <van-datetime-picker v-model="fromData.inspectDate" type="date" title="选择年月日" @cancel="showPickerq = false" @confirm="onConfirmRQ" />
            </van-popup>
            <van-field readonly v-model="JBXXfrom.belongCity" label="所属市" />
            <van-field readonly v-model="JBXXfrom.belongCountry" label="所属县" />
            <van-field readonly v-model="JBXXfrom.belongTown" label="所属镇" />
            <van-field readonly v-model="JBXXfrom.belongVillage" label="所属村" />
            <van-field readonly v-model="JBXXfrom.propertyPerson" label="产权人" />
            <van-field readonly v-model="JBXXfrom.householderIdcard" label="产权人身份证号" />
            <van-field readonly v-model="JBXXfrom.detailAddress" label="具体用途" />
            <van-field readonly v-model="JBXXfrom.buildArea" label="建筑面积(㎡)" />
            <van-field readonly v-model="JBXXfrom.buildFloor" label="建筑层数(层)" />
            <van-field v-model="isHasHouse" label="是否是无房户" placeholder="选择是否是无房户" @click="disabled?'':showPicker=true" :readonly="disabled"/>
            <van-popup v-model="showPicker" position="bottom">
                <van-picker
                    value-key="name"
                    title="选择是否是无房户"
                    show-toolbar
                    :columns="IswfhData"
                    @confirm="onConfirm"
                    @cancel="showPicker = false"
                />
            </van-popup>     
        </div>
        <div v-if="fromData.isHasHouse==0">
            <van-field type="textarea" v-model="fromData.opinion" label="意见" placeholder="请输入内容" :readonly="disabled"/>
            <div v-for="(itemUrl, index) in fileList" :key="index">
                <div v-if="itemUrl.type==='pdf'" style="padding:10px" @click="getGroupGuids(itemUrl,fileList)">
                    <div style="margin:10px 0px 0px 10px;font-size: 14px;margin-bottom: 10px;">
                        <span style="color:red">*</span>
                        {{ itemUrl.name }}
                    </div>
                <van-uploader
                    v-if="itemUrl.type==='pdf'"
                    :disabled="disabled"
                    :after-read="afterRead"
                    :before-delete="delectFile"
                    v-model="itemUrl.fileList"
                    accept=".pdf,.jpg,.gif,.png,.jpeg"
                    multiple
                />
                </div>
            </div>
        </div>
        <div v-if="fromData.isHasHouse!==0">
            <div class="XCZK">
                <p class="title">现场状况</p>
                <div v-for="(item,index) in XCZKList" :key="index">
                    <p class="subtitle">
                        {{item.name}}
                    </p>
                    <van-checkbox-group v-model="item.valueYC" :disabled="disabled">
                        <van-checkbox name="0" shape="square" @click="handleRadioChange(item)">无异常</van-checkbox>
                    </van-checkbox-group>
                    <van-checkbox-group :ref="'checkboxGroup' + index" v-model="item.value" :disabled="disabled">
                        <van-checkbox shape="square" @click="handleCheckedChange(item)" v-for="(items,index) in item.children" :key="index" :name="items.value"
                            style="margin-top:10px">{{items.name}}</van-checkbox>
                    </van-checkbox-group>
                </div>
            </div>
            <div class="XCZK">
                <p class="title">排查结论</p>
                <van-radio-group  :disabled="disabled" v-model="fromData.firstJudge">
                    <van-radio :name="0" style="margin-bottom: 10px;">基本安全</van-radio>
                    <van-radio :name="1">存在安全隐患（需要安全鉴定）</van-radio>
                </van-radio-group>
            </div>
            <div v-for="(itemUrl, index) in fileList" :key="index">
                <div v-if="itemUrl.type==='img'" style="padding:10px" @click="getGroupGuids(itemUrl,fileList)">
                    <div style="margin:10px 0px 0px 10px;font-size: 14px;margin-bottom: 10px;">
                        <span style="color:red">*</span>
                        {{ itemUrl.name }}
                    </div>
                <van-uploader
                    v-if="itemUrl.type==='img'"
                    :disabled="disabled"
                    :after-read="afterRead"
                    :before-delete="delectFile"
                    v-model="itemUrl.fileList"
                    accept=".jpg,.gif,.png,.jpeg"
                    multiple
                />
                    <!--<van-uploader  :disabled="disabled" :auto-upload="true"-->
                                <!--:http-request="afterRead" :on-remove="delectFile"  v-model="itemUrl.fileList" multiple />-->
                    <!-- <el-upload action="#" accept=".jpg, .png,.jpeg,jif" :disabled="disabled" :auto-upload="true"
                        list-type="picture-card" :file-list="itemUrl.fileList" :on-remove="delectFile"
                        :on-preview="handlePictureCardPreview" :http-request="afterRead">
                        <i class="el-icon-plus"></i>
                    </el-upload> -->
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import { ossUploadFiles, FileServerProxy,ossdelteFiles } from '@/utils/api'
export default {
    props: {
        objectNo: String,
        disabled: Boolean
    },
    name: "houseSafetyChecklist",
    data() {
        return {
            showPickerq: false,
            isHasHouse: '',
            IswfhData: [
                {
                    name: '是',
                    val: 0
                },{
                    name: '否',
                    val: 1
                }
            ],
            showPicker: false,
            BaseURL: window.g.BaseURL,
            JBXXfrom: {
                propertyPerson: "",
                householderIdcard: "",
                buildFloor: "",
                buildYear: "",
                belongCity: "",
                belongCounty: "",
                belongTown: "",
                belongVillage: "",
                detailAddress: "",
                buildArea: "",
                homesteadArea: "",
                houseUsage: "",
                isExpansion: "",
                safetyLevel: "",
                isTkFk: "",
                houseType: "",
                patrolProcessNode: 0,
                objectNo: ""
            },
            XCZKList: [{
                name: "周边情况",
                key: 'buildEnums',
                valueYC: [],
                value: [],
                children: [
                    {
                        name: '房屋周边地面长期积水',
                        value: '1'
                    },
                    {
                        name: '房屋周边有工程建设和深基坑施工情况',
                        value: '2'
                    },
                    {
                        name: '裂缝持续发展尚未稳定',
                        value: '3'
                    },
                    {
                        name: '出现明显倾斜',
                        value: '4'
                    },
                    {
                        name: '基础局部或塌陷的',
                        value: '5'
                    }
                ]
            }, {
                name: "地基基础",
                key: 'baseEnums',
                valueYC: [],
                value: [],
                children: [
                    {
                        name: '房屋出现明显不均匀沉降（斜向）裂缝',
                        value: '1'
                    },
                    {
                        name: '外露基础明显腐蚀、酥碱、松散和剥落',
                        value: '2'
                    },
                    {
                        name: '裂缝持续发展尚未稳定',
                        value: '3'
                    },
                    {
                        name: '出现明显倾斜',
                        value: '4'
                    },
                    {
                        name: '基础局部或塌陷的',
                        value: '5'
                    }
                ]
            }, {
                name: "墙体",
                key: 'liveBrickEnums',
                valueYC: [],
                value: [],
                children: [
                    {
                        name: '墙体开裂严重',
                        value: '1'
                    },
                    {
                        name: '墙体有歪斜',
                        value: '2'
                    },
                    {
                        name: '局部倒塌或有倒坍危险',
                        value: '3'
                    }
                ]
            }, {
                name: "柱、梁、板",
                key: 'livePillarsEnums',
                valueYC: [],
                value: [],
                children: [
                    {
                        name: '保护层剥落严重',
                        value: '1'
                    },
                    {
                        name: '钢筋漏筋、锈蚀，出现明显锈胀裂缝',
                        value: '2'
                    },
                    {
                        name: '梁柱出现明显受力裂缝和变形',
                        value: '3'
                    },
                ]
            }, {
                name: "楼屋面",
                key: 'liveFloorEnums',
                valueYC: [],
                value: [],
                children: [
                    {
                        name: '明显变形',
                        value: '1'
                    },
                    {
                        name: '明显裂缝',
                        value: '2'
                    },
                    {
                        name: '较严重渗漏',
                        value: '3'
                    },
                    {
                        name: '老化破损',
                        value: '4'
                    },
                ]
            }, {
                name: "木架构",
                key: 'liveWoodEnums',
                valueYC: [],
                value: [],
                children: [
                    {
                        name: '明显腐朽或虫蛀',
                        value: '1'
                    },
                    {
                        name: '梁、檩跨中明显变形或出现横向裂缝',
                        value: '2'
                    },
                    {
                        name: '梁、檩端部出现劈裂',
                        value: '3'
                    },
                    {
                        name: '柱身明显歪斜',
                        value: '4'
                    },
                    {
                        name: '木柱与柱基础之间错位',
                        value: '5'
                    },
                    {
                        name: '构件纵向有明显干缩裂缝',
                        value: '6'
                    },
                    {
                        name: '卯榫节点有破损或有拔榫迹象',
                        value: '7'
                    },
                    {
                        name: '承重柱存在接柱或转换情况且未采取可靠连接措施',
                        value: '8'
                    },
                ]
            }],
            fromData: {
                "firstJudge": "",
                "id": "",
                "inspectDate": "",
                "inspectPerson": "",
                "baseEnums": "",
                "buildEnums": "",
                "liveBrickEnums": "",
                "liveFloorEnums": "",
                "livePillarsEnums": "",
                "liveWoodEnums": "",
                "objectNo": "",
                isHasHouse: '',
                opinion: ''
            },
            fileList: [
                {
                    name: '照片',
                    groupGuid: '',
                    fileList: [],
                    type: 'img'
                },
                {
                    name: '无房证明材料',
                    groupGuid: '',
                    fileList: [],
                    type: 'pdf'
                },
            ]
        }
    },
    filters: {
        inUseName: function (msg, data) {
            let name = ''
            data.forEach((item) => {
                if (item.DICID == msg) {
                    name = item.DICNAME
                }
            })
            return name
        },
    },
    methods: {
        onConfirmRQ(val){
            let year = val.getFullYear()
            let month = val.getMonth() + 1
            let day = val.getDate()
            let hour = val.getHours()
            let minute = val.getMinutes()
            if (month >= 1 && month <= 9) {
                month = `0${month}`
            }
            if (day >= 1 && day <= 9) {
                day = `0${day}`
            }
            if (hour >= 0 && hour <= 9) {
                hour = `0${hour}`
            }
            if (minute >= 0 && minute <= 9) {
                minute = `0${minute}`
            }
            this.fromData.inspectDate = `${year}-${month}-${day}`
            this.showPickerq = false
        },
        onConfirm(val){
            this.fromData.isHasHouse = val.val
            this.isHasHouse = val.name
            this.showPicker = false
            console.log(val,this.fromData.isHasHouse,'val')
        },
        getData: async function () {
            if (this.objectNo || window.sessionStorage.getItem('objectNo')) {
                let parm = {
                    objectNo: this.objectNo || window.sessionStorage.getItem('objectNo')
                }
                let res = await axios.post(this.BaseURL + '/api/farmerHouse/housePatrol/getHouseBaseInfo', parm, {
                    headers: {
                        isOutParam: true,
                    },
                });
                if (res.data.data) {
                    this.JBXXfrom = res.data.data;
                }
                let webResult = await axios.post(this.BaseURL + '/api/farmerHouse/houseInspect/getInspectDetailInfo', parm, {
                    headers: {
                        isOutParam: true,
                    },
                });
                if (webResult.data.data) {
                    this.fromData = webResult.data.data
                    if(this.fromData.isHasHouse == 0){
                        this.isHasHouse = '是'
                    }else{
                        this.isHasHouse = '否'
                    }
                    console.log(this.fromData,'this.fromData')
                    this.fromData.inspectPerson = JSON.parse(window.localStorage.getItem("userName")).aliasName;
                    this.fromData.inspectDate = this.getDate();
                    for (var k in this.fromData) {
                        this.XCZKList.forEach(item => {
                            if (k == item.key && this.fromData[item.key] !== '') {
                                if (this.fromData[item.key] == "0") {
                                    item.valueYC = this.fromData[item.key].split(",")
                                } else {
                                    console.log(this.fromData[item.key].split(","))
                                    item.value = this.fromData[item.key].split(",")
                                }
                            }
                        })
                    }
                    this.fromData.fileGroupId ? this.fileList[0].groupGuid = this.fromData.fileGroupId : "";
                    webResult.data.data.fileGroupList.forEach(item => {
                      if(window.g.IsEnabled=="1"){
                        this.fileList[0].fileList.push({
                          // url: window.g.BaseURL4 + item.fileUrl,
                          url: window.g.OSSPriview+item.fileUrl,
                          isImage: true,
                          name: item.fileName,
                        })
                      }else{
                        this.fileList[0].fileList.push({
                          url: window.g.BaseURL + 'api/upload/oss/preview?fileId='+item.id,
                          isImage: true,
                          name: item.fileName,
                        })
                      }
                    })
                    this.fromData.noHouseFileGroupId ? this.fileList[1].groupGuid = this.fromData.noHouseFileGroupId : "";
                    webResult.data.data.noHouseFileGroupList.forEach(item => {
                      if(window.g.IsEnabled=="1"){
                        this.fileList[1].fileList.push({
                          // url: window.g.BaseURL4 + item.fileUrl,
                          url: window.g.OSSPriview+item.fileUrl,
                          isImage: true,
                          name: item.fileName,
                        })
                      }else{
                        this.fileList[1].fileList.push({
                          url: window.g.BaseURL + 'api/upload/oss/preview?fileId='+item.id,
                          isImage: true,
                          name: item.fileName,
                        })
                      }
                    })
                }
            }
        },
        saveData: async function (type) {
            if(this.fromData.isHasHouse==0&&this.fileList[1].fileList.length == 0){
                this.$toast.fail("无房证明材料")
                return
            }
            if(this.fromData.isHasHouse==1&&this.fileList[0].fileList.length == 0){
                this.$toast.fail("请先上传照片")
                return
            }
            this.XCZKList.forEach(element => {
                if (element.valueYC&&element.valueYC.length!=0) {
                    this.fromData[element.key] = element.valueYC.join(",")
                } else if (element.value.length > 0) {
                    this.fromData[element.key] = element.value.join(",")
                }
            });
            let parmData = this.fromData
            parmData['objectNo'] = this.objectNo;
            parmData['fileGroupId'] = this.fileList[0].groupGuid;
            parmData['noHouseFileGroupId'] = this.fileList[1].groupGuid;
            delete parmData.fileGroupList;
            let webResult = await axios.post(this.BaseURL + '/api/farmerHouse/houseInspect/saveInspectInfo', parmData, {
                headers: {
                    isOutParam: true,
                },
            });
            if (type == "submit") {
                this.submit()
            } else {
                if (webResult.data.data) {
                    this.$toast.success("保存成功")
                } else {
                    this.$toast.fail("保存失败")
                }
            }
        },
        //提交
        submit: async function () {
            if(this.fromData.firstJudge !== ""||this.fromData.firstJudge != null){
                let parm = {
                    objectNo: this.objectNo,
                    userName: window.localStorage.getItem("DanDianName"),
                    userId: window.localStorage.getItem("DanDianid"),
                }
                let webResult = await axios.post(this.BaseURL + '/api/farmerHouse/houseInspect/submitInspectInfo', parm, {
                    headers: {
                        isOutParam: true,
                    },
                });
                if (webResult.data.data) {
                this.$toast.success("提交成功")
                this.$router.push({
                    path: '/toBeCheckedList',
                })

                } else {
                    this.$toast.fail("提交失败")
                }
            }else{
                this.$toast.fail("请先提交排查结论")
            }
        },
        //附件
        getGroupGuids(item, list) {
            this.groupName = item.name;
            this.groupGuid = item.groupGuid;
        },
        //上传附件
        afterRead: async function (file) {
            let _this = this;
            var formData = new FormData();
            formData.append("files", file.file);
            formData.append('path', 'wg')
            formData.append("groupName", this.groupName);
            formData.append("toGroupGuid", this.groupGuid);
            const res = await ossUploadFiles(formData)
        },
        //删除附件
        delectFile: async function (file) {
            // let fileguid = ''
            // if (file.ROW_GUID) {
            //     fileguid = file.ROW_GUID
            // } else {
            //     fileguid = this.fileGuid
            // }
            // if (fileguid) {
            //     let params = {
            //         accessCode: 'ce9b691634de4ebca68dc5bb638d07f4',
            //         cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
            //         params: {
            //             fileGuid: fileguid,
            //             token: window.localStorage.getItem('token'),
            //         },
            //     }
            //     const res = await FileServerProxy(params)
            //     let data = JSON.parse(res.data.data).Success
            //     if (data) {
            //         this.$toast.success('删除成功!')
            //     }
            // }
            let arr = [];
            arr.push(file.id)
            const res = await ossdelteFiles(arr)
            this.$toast.success(res.data.msg)
        },
        //打开附件
        handlePictureCardPreview(file) {
            Eca.Window.OpenWebUrl('预览', file.url, ["85vw", "90vh"]);
        },
        //
        handleCheckedChange(item) {
            console.log(item,'item handleCheckedChange')
            if(item.value.length > 0){
                this.fromData.firstJudge = 1
            }
            item.valueYC = []
        },
        //
        handleRadioChange(item) {
            console.log(item.valueYC,this.XCZKList,this.sum,'item')
            // XCZKList
            item.value = [];
            this.XCZKList.forEach(element => {
                if (element.valueYC&&element.valueYC.length!=0) {
                    this.fromData[element.key] = element.valueYC.join(",")
                }else{
                    this.fromData[element.key] = ''
                }
            });
            if(this.fromData.buildEnums==='0'&&
                this.fromData.baseEnums==='0'&&
                this.fromData.liveBrickEnums==='0'&&
                this.fromData.livePillarsEnums==='0'&&
                this.fromData.liveFloorEnums==='0'&&
                this.fromData.liveWoodEnums==='0'){
                this.fromData.firstJudge = 0
            }else{
                this.fromData.firstJudge = 1
            }
            // item.valueYC = "0"
            // this.$refs['checkboxGroup' + index][0].toggleAll(false);
        }
    },
    mounted() {
        this.getData();
        // if(window.localStorage.getItem("userName")&&JSON.parse(
        //   window.localStorage.getItem("userName")
        // )){
        //   this.fromData.inspectPerson = JSON.parse(
        //     window.localStorage.getItem("userName")
        //   ).userName
        // }
        this.fromData.inspectPerson = JSON.parse(window.localStorage.getItem("userName")).aliasName;
        this.fromData.inspectDate = this.getDate();
        //给每个附件分组随机生成guid
        this.fileList.forEach(item => {
            item.groupGuid = this.newGuid()
        })
    }
}
</script>

<style scoped lang="scss">
#houseSafetyChecklist {
    width: 100%;

    .title {
        text-align: center;
        font-weight: bold;
        margin-bottom: 10px
    }

    .XCZK {
        padding: 10px;

        .subtitle {
            font-size: 16px;
            margin: 10px 0;
        }
    }

}
</style>
